<script setup>
import { useExperimentStore } from '@/stores/experimentStore'
import * as echarts from 'echarts'
import { ref, onMounted, watch, onBeforeUnmount, nextTick } from 'vue'

import { ElForm } from 'element-plus'
import { useTokenStore } from '@/stores/tokens'

import { ElMessage } from 'element-plus'
import { ElLoading } from 'element-plus'
import { ElMessageBox } from 'element-plus'
import api from '@/api/request'
import CommonHeader from '@/views/common/CommonHeader.vue'

const experimentStore = useExperimentStore()

const teamNameStore = useExperimentStore()
// 修改 token 获取方式
const tokenStore = useTokenStore()

const pageSize = ref(5)
const currentPage = ref(1)

const getTotalTimePoints = () => {
  // 检查 experimentStore 和 collectedExperiments 是否为 null
  if (
    !experimentStore?.collectedExperiments ||
    !experimentStore.collectedExperiments.experimentRounds
  ) {
    return 0
  }

  const rounds = experimentStore.collectedExperiments.experimentRounds
  return rounds.reduce((total, round) => {
    if (!Array.isArray(round.timePoints)) {
      return total
    }
    return (
      total +
      round.timePoints.reduce((timePointTotal, timePoint) => {
        return (
          timePointTotal +
          (Array.isArray(timePoint.groups) ? timePoint.groups.length : 0)
        )
      }, 0)
    )
  }, 0)
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const TimePoints = ref([
  {
    timePointName: '2024-11-03T16:00:00.000Z',
    groups: [
      { groupName: '正常组', infect: 0.7453 },
      { groupName: '感染组', infect: 0.9453 },
      { groupName: '疫苗组', infect: 0.3153 }
    ]
  },
  {
    timePointName: '2024-11-07T16:00:00.000Z',
    groups: [
      { groupName: '正常组', infect: 0.6453 },
      { groupName: '感染组', infect: 0.7983 },
      { groupName: '疫苗组', infect: 0.2353 }
    ]
  }
])
// 根据 TimePoints 数据提取图表所需的数据
const getChartData = () => {
  const categories = [] // X轴：groupName
  const seriesData = [] // Y轴：infect 数据

  // 遍历 TimePoints，按 groupName 汇总数据
  TimePoints.value.forEach((point) => {
    categories.push(new Date(point.timePointName).toLocaleDateString())
    point.groups.forEach((group, index) => {
      if (!seriesData[index]) {
        seriesData[index] = {
          name: group.groupName,
          type: 'line', // 折线图类型
          data: []
        }
      }
      seriesData[index].data.push(group.infect)
    })
  })

  return { categories, seriesData }
}

// 获取历史实验数据的函数
const gethistoryExperiments = async () => {
  try {
    const response = await api.post(
      '/history',
      {
        experimentName: experimentStore.collectedExperiments.experimentName
      },
      {
        headers: {
          'Content-Type': 'application/json',
          token: tokenStore.token
        }
      }
    )
    console.log('历史实验数据:', response.data)
    // 更新 TimePoints 数据
    if (response.data && response.data.data) {
      TimePoints.value = response.data.data.timePoints || []
    }
  } catch (error) {
    console.error(
      '获取历史实验数据失败：',
      error.response?.data || error.message
    )
    ElMessage.error('获取历史实验数据失败')
  }
}

// 观察 TimePoints 的变化以重新绘制图表
watch(
  TimePoints,
  (newValue) => {
    if (newValue && newValue.length > 0) {
      nextTick(() => {
        initCharts()
      })
    }
  },
  { deep: true }
)
//中间部分的图表charts
const radios = ref(2)
// 引用 DOM 元素
const pieChart = ref(null)
const barChart = ref(null)
const lineChart = ref(null)
const lineChart2 = ref(null) // 第二个折线图
// 公共样式配置
const chartStyle = {
  title: {
    textStyle: {
      fontSize: 18,
      fontWeight: 'bold',
      color: '#333'
    },
    left: 'center',
    top: 20
  },
  tooltip: {
    trigger: 'axis',
    backgroundColor: 'rgba(255, 255, 255, 0.9)',
    borderColor: '#ccc',
    borderWidth: 1,
    textStyle: {
      color: '#333'
    },
    padding: [10, 15]
  },
  legend: {
    orient: 'horizontal',
    bottom: 10,
    textStyle: {
      fontSize: 12,
      color: '#666'
    },
    itemGap: 20
  },
  grid: {
    top: 80,
    bottom: 60,
    left: '10%',
    right: '10%',
    containLabel: true
  }
}

// 初始化图表的方法
const initCharts = () => {
  nextTick(() => {
    if (radios.value === 1) {
      initLineChart2() // 折线图
    } else if (radios.value === 2) {
      initPieChart() // 饼状图
      initBarChart() // 柱状图
      initLineChart()
    }
  })
}

// 初始化饼状图
// 初始化饼图
const initPieChart = () => {
  const groupSums = {}
  TimePoints.value.forEach((point) => {
    point.groups.forEach((group) => {
      if (!groupSums[group.groupName]) {
        groupSums[group.groupName] = 0
      }
      groupSums[group.groupName] += group.infect
    })
  })

  const pieData = Object.entries(groupSums).map(([name, value]) => ({
    name,
    value
  }))

  // 获取饼图的 DOM 元素
  const pieChartElement = pieChart.value

  // 如果存在之前的图表实例，先销毁它
  if (pieChartElement) {
    echarts.dispose(pieChartElement)
  }

  // 创建新的图表实例
  const pieInstance = echarts.init(pieChartElement)
  const pieOption = {
    title: {
      ...chartStyle.title,
      text: '感染率占比饼状图'
    },
    tooltip: {
      trigger: 'item',
      ...chartStyle.tooltip
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      ...chartStyle.legend
    },
    series: [
      {
        name: '感染率',
        type: 'pie',
        radius: '50%',
        data: pieData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  pieInstance.setOption(pieOption)
}

// 初始化柱状图
const initBarChart = () => {
  const { categories, seriesData } = getChartData()

  // 获取柱状图的 DOM 元素
  const barChartElement = barChart.value

  // 如果存在之前的图表实例，先销毁它
  if (barChartElement) {
    echarts.dispose(barChartElement)
  }

  // 创建新的图表实例
  const barInstance = echarts.init(barChartElement)
  const barOption = {
    title: {
      ...chartStyle.title,
      text: '感染率柱状图'
    },
    tooltip: {
      ...chartStyle.tooltip
    },
    legend: {
      ...chartStyle.legend
    },
    xAxis: {
      type: 'category',
      data: categories, // 时间点作为 X 轴
      axisLabel: {
        rotate: 45 // 旋转 X 轴标签
      }
    },
    yAxis: { type: 'value' },
    series: seriesData.map((series) => ({
      ...series,
      type: 'bar' // 设置为柱状图
    }))
  }
  barInstance.setOption(barOption)
}

// 修改条形图的初始化函数
const initLineChart = () => {
  const yAxisData = [] // y 轴（组名称）
  const seriesData = [] // 各时间点的数据

  // 动态生成数据
  TimePoints.value.forEach((timePoint, timeIndex) => {
    timePoint.groups.forEach((group) => {
      if (!yAxisData.includes(group.groupName)) {
        yAxisData.push(group.groupName) // 添加组名到 yAxisData
      }
      // 确保每个时间点的数据已初始化
      if (!seriesData[timeIndex]) {
        seriesData[timeIndex] = {
          name: `时间点 ${timeIndex + 1}`, // 时间点名称
          type: 'bar', // 设置为条形图
          data: [],
          barWidth: '30%',
          itemStyle: {
            // 设置每个时间点不同的颜色
            color: ['#5470C6', '#91CC75', '#FAC858'][timeIndex % 3]
          }
        }
      }
      // 为每个时间点添加数据
      seriesData[timeIndex].data.push(group.infect)
    })
  })

  // 获取图表的 DOM 元素
  const lineChartElement = lineChart.value

  // 如果图表已经存在，先销毁它
  if (lineChartElement) {
    echarts.dispose(lineChartElement)
  }

  // 创建新的图表实例
  const lineInstance = echarts.init(lineChartElement)

  const lineOption = {
    title: {
      text: '感染率条形图',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      bottom: 0
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: yAxisData,
      axisLabel: {
        inside: false, // 确保标签在轴外部
        margin: 16 // 增加标签与轴的距离
      }
    },
    grid: {
      top: '10%',
      bottom: '15%',
      left: '25%', // 显著增加左侧空间
      right: '10%',
      containLabel: true
    },
    series: seriesData
  }

  // 设置图表选项
  lineInstance.setOption(lineOption)
}

// 初始化折线图
const initLineChart2 = () => {
  const xAxisData = [] // x轴（时间点）
  const seriesData = [] // 存储每个组的数据
  const groupMap = new Map() // 用于存储每个组的索引

  // 确保 TimePoints 有数据
  if (!TimePoints.value || TimePoints.value.length === 0) {
    console.warn('No data available for chart')
    return
  }

  // 首先收集所有时间点和组名
  TimePoints.value.forEach((timePoint) => {
    // 格式化日期显示
    const date = new Date(timePoint.timePointName)
    xAxisData.push(date.toLocaleDateString())

    timePoint.groups.forEach((group) => {
      if (!groupMap.has(group.groupName)) {
        groupMap.set(group.groupName, seriesData.length)
        seriesData.push({
          name: group.groupName,
          type: 'line',
          data: new Array(TimePoints.value.length).fill(null),
          smooth: true,
          lineStyle: { width: 2 },
          itemStyle: {
            color: ['#5470C6', '#91CC75', '#FAC858'][groupMap.size % 3]
          }
        })
      }
    })
  })

  // 填充数据
  TimePoints.value.forEach((timePoint, timeIndex) => {
    timePoint.groups.forEach((group) => {
      const seriesIndex = groupMap.get(group.groupName)
      if (seriesIndex !== undefined) {
        seriesData[seriesIndex].data[timeIndex] = group.infect
      }
    })
  })

  // 获取折线图的 DOM 元素
  const lineChartElement = lineChart2.value
  if (!lineChartElement) {
    console.error('Chart element not found')
    return
  }

  echarts.dispose(lineChartElement)

  // 创建新的图表实例
  const lineInstance = echarts.init(lineChartElement)
  const lineOption = {
    title: {
      text: '感染率折线图',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      ...chartStyle.tooltip
    },
    legend: {
      orient: 'horizontal',
      bottom: 0,
      ...chartStyle.legend
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 1,
      splitLine: {
        show: true
      }
    },
    grid: {
      top: 60,
      bottom: 60,
      left: '10%',
      right: '10%'
    },
    series: seriesData
  }

  lineInstance.setOption(lineOption)
}

// 监听窗口大小变化
const resizeCharts = () => {
  echarts.getInstanceByDom(pieChart.value)?.resize()
  echarts.getInstanceByDom(barChart.value)?.resize()
  echarts.getInstanceByDom(lineChart.value)?.resize()
  if (lineChart2.value) {
    echarts.getInstanceByDom(lineChart2.value)?.resize()
  }
}

// 确保在组件销毁时移除事件监听
onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeCharts)
})

// 添加数据监听以自动更新图表
watch(
  TimePoints,
  (newValue) => {
    if (newValue && newValue.length > 0) {
      nextTick(() => {
        initCharts()
      })
    }
  },
  { deep: true }
)

const isCharts = ref(true)
const isShowForm = ref(false)
const buttonName = ref('查看详细数据')
const isDisabled = ref(false)

// 修改 showForm 函数
const showForm = async () => {
  console.log('showForm clicked')
  isShowForm.value = !isShowForm.value
  isCharts.value = !isCharts.value
  isDisabled.value = isShowForm.value

  buttonName.value = isShowForm.value ? '查看图表' : '查看详细数据'

  if (isShowForm.value) {
    try {
      const response = await api.post(
        '/detail',
        {
          experimentName: experimentStore.collectedExperiments?.experimentName
        },
        {
          headers: {
            'Content-Type': 'application/json',
            token: tokenStore.token
          }
        }
      )
      console.log('接收到的数据:', response.data.data)
      // 确保数据格式正确
      if (response.data.data.experimentRounds) {
        experimentStore.updateExperimentData(response.data.data)
      } else {
        throw new Error('数据格式不正确')
      }
    } catch (error) {
      console.error('请求失败:', error)
      ElMessage.error(error.message || '获取详细数据失败')
      // 发生错误时恢复原始状态
      isShowForm.value = false
      isCharts.value = true
      isDisabled.value = false
      buttonName.value = '查看详细数据'
    }
  }
}

// 控制弹窗显示状态
const isViewFileDialogVisible = ref(false)

// 存储表单数据
const viewFormData = ref({
  roundName: '',
  timePointName: '',
  groupName: '',
  fileUrls: [] // 存储当前组的文件链接
})

async function viewFiles(group, round, timePointName) {
  viewFormData.value = {
    roundName: round.roundName,
    timePointName,
    groupName: group.groupName,
    fileUrls: []
  }

  isViewFileDialogVisible.value = true

  try {
    const response = await api.post(
      '/detail/specific',
      {
        experimentName: experimentStore.collectedExperiments.experimentName,
        roundName: round.roundName,
        timePointName: timePointName,
        groupName: group.groupName
      },
      {
        headers: {
          'Content-Type': 'application/json',
          token: tokenStore.token
        }
      }
    )

    if (response.data && response.data.data) {
      // 直接使用后端返回的图片 URL
      viewFormData.value.fileUrls = response.data.data
    } else {
      ElMessage.warning('没有可显示的图片')
    }
  } catch (error) {
    console.error('获取图片失败:', error)
    ElMessage.error('获取图片失败，请重试')
  }
}

// 修改分页函数来正确处理跨时间点的组分页
const getPaginatedGroups = (groups) => {
  if (!groups) return []

  // 计算当前组在所有组中的起始位置
  let totalIndex = 0
  let foundCurrentGroups = false

  for (const round of experimentStore.collectedExperiments.experimentRounds) {
    for (const timePoint of round.timePoints) {
      if (timePoint.groups === groups) {
        foundCurrentGroups = true
        break
      }
      totalIndex += timePoint.groups?.length || 0
    }
    if (foundCurrentGroups) break
  }

  // 计算当前页的起始和结束索引
  const pageStartIndex = (currentPage.value - 1) * pageSize.value
  const pageEndIndex = pageStartIndex + pageSize.value

  // 检查当前组是否应该在当前页显示
  if (
    totalIndex + groups.length <= pageStartIndex ||
    totalIndex >= pageEndIndex
  ) {
    return [] // 当前组不在当前页范围内
  }

  // 计算当前组需要显示的部分
  const startSlice = Math.max(0, pageStartIndex - totalIndex)
  const endSlice = Math.min(groups.length, pageEndIndex - totalIndex)

  return groups.slice(startSlice, endSlice)
}

// 添加一个新的函数来检查时间点是否应该显示
const shouldShowTimePoint = (timePoint) => {
  if (!timePoint.groups) return false
  const paginatedGroups = getPaginatedGroups(timePoint.groups)
  return paginatedGroups.length > 0
}

// 添加计算属性来过滤时间点
const getFilteredTimePoints = (timePoints) => {
  if (!timePoints) return []
  return timePoints.filter((timePoint) => shouldShowTimePoint(timePoint))
}

// 添加用于存储用户输入的图片名称
const customImageName = ref('')

// 控制图片名称输入弹窗的显示状态
const isImageNameDialogVisible = ref(false)

// 保存图表的函数
const saveCharts = async () => {
  try {
    // 显示图片名称输入弹窗
    isImageNameDialogVisible.value = true

    // 等待用户输入图片名称
    await new Promise((resolve) => {
      const unwatch = watch(isImageNameDialogVisible, (newValue) => {
        if (!newValue) {
          unwatch()
          resolve()
        }
      })
    })

    const loading = ElLoading.service({
      text: '正在保存图表...'
    })

    // 获取所有图表实例
    const charts = []
    if (radios.value === 1) {
      charts.push({
        name: '变化趋势图',
        instance: echarts.getInstanceByDom(lineChart2.value)
      })
    } else if (radios.value === 2) {
      charts.push(
        {
          name: '饼状图',
          instance: echarts.getInstanceByDom(pieChart.value)
        },
        {
          name: '柱状图',
          instance: echarts.getInstanceByDom(barChart.value)
        },
        {
          name: '条形图',
          instance: echarts.getInstanceByDom(lineChart.value)
        }
      )
    }

    // 创建 FormData 对象
    const formData = new FormData()
    formData.append(
      'experimentName',
      experimentStore.collectedExperiments.experimentName
    )
    formData.append('values', customImageName.value || '图表')

    // 将每个图表转换为base64图片并添加到 FormData
    for (const chart of charts) {
      if (!chart.instance) continue

      // 将图表转换为base64
      const base64 = chart.instance.getDataURL({
        type: 'png',
        pixelRatio: 2
      })

      // 将base64转换为Blob
      const blob = await (await fetch(base64)).blob()
      const fileName = `${customImageName.value || chart.name}_${Date.now()}.png`

      // 将 Blob 转换为 File
      const file = new File([blob], fileName, { type: 'image/png' })

      // 添加到 FormData
      formData.append('multipartFiles', file)
    }

    // 打印 FormData 内容
    for (let pair of formData.entries()) {
      console.log(pair[0] + ', ' + pair[1])
    }

    try {
      console.log('formData', formData)
      // 调用 /savesacleimage 接口上传
      const response = await api.post('/savesacleimage', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          token: tokenStore.token
        }
      })

      if (response.data.code === 200) {
        ElMessage.success('图表保存成功')
      } else {
        ElMessage.error('图表保存失败')
      }
    } catch (error) {
      console.error('上传图表失败:', error)
      ElMessage.error('上传图表失败')
    }

    loading.close()
  } catch (error) {
    console.error('保存图表过程出错:', error)
    ElMessage.error('保存图表失败')
  }
}

// 添加删除组的函数
const deleteGroup = async (group, timePoint, round) => {
  try {
    const confirmResult = await ElMessageBox.confirm(
      '确定要删除这个组吗？此操作不可逆',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    if (confirmResult === 'confirm') {
      const loading = ElLoading.service({
        text: '正在删除...'
      })

      try {
        // 调用后端接口删除组
        await api.post(
          '/detail/specific/delete',
          {
            experimentName: experimentStore.collectedExperiments.experimentName,
            roundName: round.roundName,
            timePointName: timePoint.timePointName,
            groupName: group.groupName
          },
          {
            headers: {
              'Content-Type': 'application/json',
              token: tokenStore.token
            }
          }
        )

        // 从本地数据中删除该组
        const groupIndex = timePoint.groups.findIndex((g) => g === group)
        if (groupIndex !== -1) {
          timePoint.groups.splice(groupIndex, 1)
        }

        // 如果时间点没有组了，也删除时间点
        if (timePoint.groups.length === 0) {
          const timePointIndex = round.timePoints.findIndex(
            (tp) => tp === timePoint
          )
          if (timePointIndex !== -1) {
            round.timePoints.splice(timePointIndex, 1)
          }
        }

        ElMessage.success('删除成功')
      } catch (error) {
        console.error('删除失败:', error)
        ElMessage.error(
          `删除失败: ${error.response?.data?.message || error.message || '未知错误'}`
        )
      } finally {
        loading.close()
      }
    }
  } catch (error) {
    // 用户取消删除操作
    console.log('用户取消删除')
  }
}

// 添加数据监听
watch(
  () => experimentStore.collectedExperiments,
  (newValue) => {
    if (newValue) {
      // 当数据更新时重新计算总数
      getTotalTimePoints()
    }
  },
  { deep: true }
)

onMounted(() => {
  // 获取 URL query 中的 data 字段
  const dataString = new URLSearchParams(window.location.search).get('data')

  // 如果 data 字段存在，解析成对象
  if (dataString) {
    try {
      // 将接收到的 JSON 字符串转换为对象
      const parsedData = JSON.parse(dataString)

      // 替换 TimePoints 数据，注意这里要处理 Timepoints（首字母大写）
      if (parsedData && parsedData.data && parsedData.data.Timepoints) {
        // 转换数据格式
        TimePoints.value = parsedData.data.Timepoints.map((timepoint) => ({
          timePointName: new Date(timepoint.timePointName).toISOString(),
          groups: timepoint.groups.map((group) => ({
            groupName: group.groupName,
            infect: parseFloat(group.infect)
          }))
        }))
      }
    } catch (error) {
      console.error('JSON parse error:', error)
      ElMessage.error('数据解析失败')
    }
  }

  // 确保在数据加载后初始化图表
  nextTick(() => {
    initCharts()
  })
})

onMounted(async () => {
  nextTick(() => {
    initCharts() // 确保 DOM 挂载后初始化图表
    window.addEventListener('resize', resizeCharts)
  })

  // 获取团队列表
  await teamNameStore.fetchTeamList()

  // 获取历史实验数据
  await gethistoryExperiments()
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeCharts)
})
</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-container>
        <CommonHeader />
        <el-main>
          <!-- 中间部分的图表容器 -->
          <div class="chart-container" v-show="isCharts">
            <!-- 当选择"同时间对比"时，显示饼状图、柱状图和条形图 -->
            <div v-if="radios === 2" ref="pieChart" class="chart"></div>
            <div v-if="radios === 2" ref="barChart" class="chart"></div>
            <div v-if="radios === 2" ref="lineChart" class="chart"></div>

            <!-- 当选择"变化趋势"时，显示折线图 -->
            <div v-if="radios === 1" ref="lineChart2" class="chart2"></div>
          </div>
          <!--  实验列表-->
          <el-main v-show="isShowForm">
            <div class="banner">
              <div class="container">
                <el-table
                  :data="experimentStore.collectedExperiments.experimentRounds"
                  style="width: 100%; margin-bottom: 20px"
                >
                  <el-table-column label="实验轮次" width="150">
                    <template #default="{ row }">
                      <span>{{ row.roundName }}</span>
                    </template>
                  </el-table-column>

                  <el-table-column label="时间点和组信息" width="auto">
                    <template #default="{ row }">
                      <div
                        v-for="timePoint in getFilteredTimePoints(
                          row.timePoints
                        )"
                        :key="timePoint.timePointName"
                      >
                        <el-date-picker
                          v-model="timePoint.timePointName"
                          type="datetime"
                          placeholder="选择时间"
                          disabled
                        ></el-date-picker>

                        <div
                          v-for="(group, groupIndex) in getPaginatedGroups(
                            timePoint.groups
                          )"
                          :key="groupIndex"
                          class="group-info"
                        >
                          <div class="group-item">
                            <div class="group-header">
                              <span>组名: {{ group.groupName }}</span>
                              <el-button
                                type="danger"
                                size="small"
                                @click="deleteGroup(group, timePoint, row)"
                                class="delete-button"
                              >
                                删除
                              </el-button>
                            </div>
                            <div
                              v-if="
                                group.fileUrls && group.fileUrls.trim() !== ''
                              "
                            >
                              <el-button
                                @click="
                                  viewFiles(group, row, timePoint.timePointName)
                                "
                                size="mini"
                                type="primary"
                                class="view-file-button"
                              >
                                查看文件图片
                              </el-button>
                            </div>
                            <div v-else>
                              <span>没有文件链接</span>
                            </div>
                          </div>
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>

                <el-pagination
                  v-model:current-page="currentPage"
                  v-model:page-size="pageSize"
                  :page-sizes="[5, 10, 20, 50]"
                  :total="getTotalTimePoints()"
                  layout="total, sizes, prev, pager, next, jumper"
                  :pager-count="5"
                  prev-text="上一页"
                  next-text="下一页"
                  total-text="总条目"
                  size-change-text="条/页"
                  jump-text="前往"
                  class="pagination"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </div>

            <!-- 弹出的表单，展示当前组的所有信息 -->
            <el-dialog
              v-model="isViewFileDialogVisible"
              title="查看文件图片"
              width="80%"
            >
              <el-form :model="viewFormData" label-width="100px">
                <el-form-item label="实验轮次">
                  <span>{{ viewFormData.roundName }}</span>
                </el-form-item>
                <el-form-item label="时间点">
                  <span>{{ viewFormData.timePointName }}</span>
                </el-form-item>
                <el-form-item label="组名">
                  <span>{{ viewFormData.groupName }}</span>
                </el-form-item>
                <el-form-item label="文件图片">
                  <el-scrollbar style="max-height: 400px; overflow-y: auto">
                    <div
                      v-if="
                        viewFormData.fileUrls &&
                        viewFormData.fileUrls.length > 0
                      "
                      class="image-container"
                    >
                      <!-- 
                      使用 el-image 组件展示图片
                      :preview-src-list 属性设置预览图片列表,点击图片时会以画廊模式显示
                      将所有图片URL传入 preview-src-list 实现图片预览功能
                      -->
                      <el-image
                        v-for="(url, index) in viewFormData.fileUrls"
                        :key="index"
                        :src="url"
                        :preview-src-list="viewFormData.fileUrls"
                        fit="contain"
                        class="image-item"
                        style="width: 300px; height: 300px; margin: 20px"
                      >
                        <template #error>
                          <div class="image-error">
                            <el-icon><Picture /></el-icon>
                            <div>图片加载失败</div>
                          </div>
                        </template>
                      </el-image>
                    </div>
                    <div v-else class="no-image">
                      <el-empty description="没有文件图片可显示" />
                    </div>
                  </el-scrollbar>
                </el-form-item>
              </el-form>

              <template v-slot:footer>
                <span class="dialog-footer">
                  <el-button @click="isViewFileDialogVisible = false"
                    >关闭</el-button
                  >
                </span>
              </template>
            </el-dialog>
          </el-main>
        </el-main>
        <el-footer>
          <div class="box">
            <el-row :gutter="20" class="all">
              <el-col :span="4">
                <el-container>
                  <el-aside style="width: 230px; margin-left: 10px">
                    实验名称:
                    <el-input
                      style="width: 140px; margin: 20px 5px"
                      placeholder="请输入实验名称"
                      v-model="
                        experimentStore.collectedExperiments.experimentName
                      "
                    />
                    <br />

                    团队名称:
                    <el-cascader
                      :options="teamNameStore.teamOptions"
                      style="width: 140px; margin: 20px 5px"
                      v-model="teamNameStore.teamName"
                    />
                  </el-aside>
                </el-container>
              </el-col>

              <el-col :span="2" class="vertical-center"> </el-col>

              <div style="margin-top: 10px">测试方法</div>

              <el-col :span="5">
                <el-aside style="margin: 50px 5px">
                  <el-row>
                    <el-radio-group
                      v-model="radios"
                      type="vertical"
                      style="
                        display: flex;
                        flex-flow: column nowrap;
                        align-items: flex-start;
                      "
                      @change="initCharts"
                    >
                      <el-radio :value="1" :disabled="isDisabled"
                        >变化趋势</el-radio
                      >
                      <el-radio :value="2" :disabled="isDisabled"
                        >同时间对比</el-radio
                      >
                    </el-radio-group>
                  </el-row>
                </el-aside>
              </el-col>

              <el-col :span="4" class="vertical-center">
                <div>
                  <el-button
                    type="primary"
                    class="action-button"
                    @click="showForm"
                  >
                    {{ buttonName }}
                  </el-button>
                </div>
              </el-col>

              <el-col :span="2" class="vertical-center">
                <el-button
                  type="success"
                  @click="saveCharts"
                  :disabled="!isCharts"
                >
                  保存图表
                </el-button>
              </el-col>
            </el-row>
          </div></el-footer
        >
      </el-container>
    </el-container>
  </div>

  <!-- 图片名称输入弹窗 -->
  <el-dialog
    v-model="isImageNameDialogVisible"
    title="输入图片名称"
    width="30%"
  >
    <el-input v-model="customImageName" placeholder="请输入图片名称"></el-input>
    <template #footer>
      <el-button @click="isImageNameDialogVisible = false">确定</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.common-layout {
  min-height: 100vh;
  background-color: #f8f8fb;

  .el-container {
    height: 100%;
  }

  .el-main {
    padding: 32px;
  }
}

.chart-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
  padding: 32px;
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(115, 103, 240, 0.08);
  margin-bottom: 24px;

  .chart {
    min-height: 400px;
    background: #ffffff;
    border-radius: 16px;
    padding: 24px;
    box-shadow: 0 4px 24px rgba(115, 103, 240, 0.08);
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 8px 32px rgba(115, 103, 240, 0.12);
    }
  }

  .chart2 {
    grid-column: 1 / -1;
    min-height: 500px;
    background: #ffffff;
    border-radius: 16px;
    padding: 24px;
    box-shadow: 0 4px 24px rgba(115, 103, 240, 0.08);
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 8px 32px rgba(115, 103, 240, 0.12);
    }
  }
}

.banner {
  padding: 32px;
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(115, 103, 240, 0.08);
  margin-bottom: 24px;

  .container {
    max-width: 1200px;
    margin: 0 auto;

    .el-table {
      border-radius: 8px;
      overflow: hidden;
      margin-bottom: 24px;

      th {
        background-color: #f8f8fb !important;
        color: #1e1e2d;
        font-weight: 600;
        padding: 16px 24px;
      }

      td {
        padding: 16px 24px;
        color: #6e6b7b;
      }
    }
  }
}

.group-info {
  background: #ffffff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 12px rgba(115, 103, 240, 0.08);
  transition: all 0.3s;

  .group-item {
    background: #f8f8fb;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 16px;
    border: 1px solid rgba(115, 103, 240, 0.1);

    .group-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      span {
        font-size: 16px;
        font-weight: 500;
        color: #1e1e2d;
      }
    }

    .el-button {
      padding: 8px 16px;
      border-radius: 6px;
      transition: all 0.3s;

      &.delete-button {
        background: #ffffff;
        border: 1px solid #ff4d4f;
        color: #ff4d4f;

        &:hover {
          background: #ff4d4f;
          color: #ffffff;
          transform: translateY(-2px);
          box-shadow: 0 4px 16px rgba(255, 77, 79, 0.3);
        }
      }

      &.view-file-button {
        background: linear-gradient(135deg, #7367f0 0%, #9f94ff 100%);
        border: none;
        color: #ffffff;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 16px rgba(115, 103, 240, 0.3);
        }
      }
    }
  }
}

.el-footer {
  background: #ffffff;
  padding: 24px;
  box-shadow: 0 -2px 12px rgba(115, 103, 240, 0.08);

  .box {
    background: #ffffff;
    border-radius: 16px;
    box-shadow: 0 4px 24px rgba(115, 103, 240, 0.08);

    .all {
      padding: 24px;
      background: linear-gradient(to right, #f8f8fb, #ffffff);
      border-radius: 16px;
      display: flex;
      align-items: center;
      gap: 24px;

      .el-col {
        display: flex;
        align-items: center;
      }

      .el-input,
      .el-cascader {
        width: 200px;
      }

      .el-radio-group {
        margin: 0 24px;
      }

      .action-button {
        background: linear-gradient(135deg, #7367f0 0%, #9f94ff 100%);
        border: none;
        padding: 12px 24px;
        border-radius: 8px;
        color: #ffffff;
        transition: all 0.3s;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 16px rgba(115, 103, 240, 0.3);
        }
      }
    }
  }
}

.el-dialog {
  border-radius: 16px;
  overflow: hidden;

  .el-dialog__header {
    margin: 0;
    padding: 20px 24px;
    border-bottom: 1px solid rgba(115, 103, 240, 0.1);
    background: linear-gradient(to right, #f8f8fb, #ffffff);
  }

  .el-dialog__body {
    padding: 24px;
  }

  .image-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 24px;
    padding: 16px;

    .el-image {
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 4px 24px rgba(115, 103, 240, 0.08);
      transition: all 0.3s;

      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 32px rgba(115, 103, 240, 0.12);
      }
    }
  }
}

.pagination {
  margin-top: 24px;
  padding: 16px;
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(115, 103, 240, 0.08);
  display: flex;
  justify-content: flex-end;
  align-items: center;

  :deep(.el-pagination) {
    .el-pagination__total {
      margin-right: 16px;
    }

    .el-pagination__sizes {
      margin-right: 16px;
    }

    .el-pager li {
      background: transparent;
      color: #6e6b7b;

      &.is-active {
        color: #7367f0;
        background: rgba(115, 103, 240, 0.1);
      }

      &:hover {
        color: #7367f0;
      }
    }
  }
}
</style>
